package common;
import manager.fileupload.service.FileUploadService;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageBase64Utils {
    public static String base64Img(String imgURL, String type, FileUploadService fileUploadService) throws IOException {
         String imagesUrl="";
        InputStream inStream=null;
        try {
                 URL url = new URL(imgURL);
                 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                 conn.setRequestMethod("GET");
                 conn.setConnectTimeout(10 * 1000);
                 if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                     return "fail";
                 }
                 inStream = conn.getInputStream();
                 File file=getTemplateFile(inStream);
                 imagesUrl=fileUploadService.uploadImageByStream(file);
                 inStream.close();
         } catch (Exception e) {
            if(inStream!=null) {
                inStream.close();
            }
         }finally {
            if(inStream!=null){
                inStream.close();
            }
         }
         if(type.equals("1")){
             return "<p><img src="+imagesUrl+"></p>";
         }
         return imagesUrl;
    }
    //获取临时文件
    public static File getTemplateFile(InputStream inputStream) {
        File file = null;
        try {
            file = File.createTempFile("temp_image", null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        inputStreamToFile(inputStream, file);
        if (file.exists() && file.length() <= 0) {
            return null;
        }
        return file;
    }
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            try {
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
            } finally {
                if (os != null) {
                    os.close();
                }
                if (ins != null) {
                    ins.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}